package com.example.service;

import com.example.model.Cart;
import com.example.model.CartItem;
import com.example.repository.CartRepository;
import com.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class CartService {

    private final CartRepository cartRepository;
    private final ProductRepository productRepository;

    @Autowired
    public CartService(CartRepository cartRepository, ProductRepository productRepository) {
        this.cartRepository = cartRepository;
        this.productRepository = productRepository;
    }

    public Cart getCart(String userId) throws IOException {
        List<CartItem> items = cartRepository.getCartItems(userId);
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setItems(items);
        return cart;
    }

    public void addItemToCart(String userId, String productId, int quantity) throws IOException {
        // Ensure product exists before adding to cart
        productRepository.findById(productId)
            .orElseThrow(() -> new IllegalArgumentException("Product not found: " + productId));

        List<CartItem> currentItems = cartRepository.getCartItems(userId);

        // Check if item already exists in cart
        for (CartItem item : currentItems) {
            if (item.getProduct().getId().equals(productId)) {
                // Item exists, update quantity
                int newQuantity = item.getQuantity() + quantity;
                cartRepository.updateItemQuantity(userId, productId, newQuantity);
                return; // Exit after updating
            }
        }

        // Item does not exist, add as new
        cartRepository.addItem(userId, productId, quantity);
    }

    public void updateCartItem(String userId, String productId, int quantity) throws IOException {
        cartRepository.updateItemQuantity(userId, productId, quantity);
    }

    public void removeItemFromCart(String userId, String productId) throws IOException {
        cartRepository.removeItem(userId, productId);
    }

    public void clearCart(String userId) throws IOException {
        cartRepository.clearCart(userId);
    }

    public List<com.example.model.Cart> getAllCarts() throws IOException {
        return cartRepository.findAllCarts();
    }
} 